import requests,re,time
# 创建保持登录凭据的session信息
login_session=requests.session()
# 发送get请求，获取token信息
token_url='http://account.chinaunix.net/login'
header={
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Encoding':'gzip, deflate',
    'Accept-Language':'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'Connection':'keep-alive',
    'Cookie':'account_chinauni=accountchinauni; XSRF-TOKEN=7Cuo0o4e3fkiwtu2u9Gd4X6nThsoTUTRH4vqFC45; laravel_session=3eCdgf8X3d3iTGo7IMpYeejgb0NPJSLONv5uaxjk',
    'Host':'account.chinaunix.net',
    'Upgrade-Insecure-Requests':'1',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55'
}
token_response=login_session.get(url=token_url,headers=header)
# 通过正则表达式匹配提取token值
token_search=re.compile(r'XSRF-TOKEN=(.*?);')
token_value=token_search.search(token_response.headers.get('Set-Cookie'))
print(token_value.group(1))
# 发送post请求
login_url='http://account.chinaunix.net/login/login'
data={
    'username':'viscaria',
    'password':'1c2c3t4v',
    '_token':token_value,
    '_t':int(time.time())
}
login_response=login_session.post(url=login_url,headers=header,data=data)
print(login_response.content)
# 获取跳转页面
index_url='http://account.chinaunix.net/ucenter/user/index'
index_response=login_session.get(url=index_url,headers=header)
print(index_response.text)
